package com.briup.cms.web.interceptor;

import com.briup.cms.exception.CustomException;
import com.briup.cms.util.JwtUtil;
import com.briup.cms.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录校验拦截器
 */
@Slf4j  //通过lombok 提供当前类中需要日志对象
@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入jwt拦截");
        //如果是预检请求：不需要进行认证信息判断
        if("OPTIONS".equals(request.getMethod())){
            return true;//通过拦截
        }

        //获取被拦截的资源名称
        String uri = request.getRequestURI();
        //使用日志方式打印执行过程
        log.info("拦截的请求url:{}",uri);

        //获取请求头信息token
        String token = request.getHeader("token");
        if(token == null){
            throw new CustomException(ResultCode.TOKEN_IS_BLANK);
        }
        //通过JWT工具类校验是否有效
        JwtUtil.parseJWT(token);
        return true;//拦截通过
    }
}
